define(['ionic'], function () {
    var myApp = angular.module('myApp', ['ionic']);
    myApp.run(function () {
        /*angular.element(document.querySelector('.backdrop')).remove();
         angular.element(document.querySelector('.loading-container')).remove();*/
    })
    myApp.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
        $stateProvider
            .state('home', {
                url: "/home",
                cache: false,
                templateUrl: "view/home.html",
                controller: 'HomeCtrl',
                resolve: {
                    'initRecords': ['$q', 'RecordsService', function ($q, RecordsService) {
                        var defer = $q.defer();
                        u9.showLoading();
                        RecordsService.loadAllRecords().then(function () {
                            defer.resolve();
                        }, function () {
                            defer.resolve();
                        }).finally(function () {
                            u9.hideLoading();
                        });
                        return defer.promise;
                    }]
                }
            })
            .state('abnormalAll', {
                url: "/abnormalAll",
                templateUrl: "view/abnormalAll.html",
                controller: 'abnormalAllCtrl',
                resolve: {
                    'loadSelectData': ['$q', 'RecordsService', function ($q, RecordsService) {
                        var defer = $q.defer();
                        u9.showLoading();
                        RecordsService.loadAllSelectData().then(function () {
                            defer.resolve();
                        }, function () {
                            //u9.alert('加载数据失败');
                            defer.resolve();
                        }).finally(function () {
                            u9.hideLoading();
                        });

                        return defer.promise;
                    }]
                }
            })
            .state('abnormalSingle', {
                url: "/abnormalSingle",
                templateUrl: "view/abnormalSingle.html",
                controller: 'abnormalSingleCtrl',
                resolve: {
                    'loadSelectData': ['$q', 'RecordsService', function ($q, RecordsService) {
                        var defer = $q.defer();
                        u9.showLoading();
                        RecordsService.loadAllSelectData().then(function () {
                            defer.resolve();
                        }, function () {
                            //u9.alert('加载数据失败');
                            defer.resolve();
                        }).finally(function () {
                            u9.hideLoading();
                        });

                        return defer.promise;
                    }]
                }
            })
            .state('abnormalDetail', {
                url: "/abnormalDetail",
                templateUrl: "view/abnormalDetail.html",
                controller: 'abnormalDetailCtrl'
            });
        $urlRouterProvider.otherwise("/home");

        $ionicConfigProvider.platform.android.navBar.alignTitle('center');
        $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
        $ionicConfigProvider.platform.android.navBar.transition('view');
        $ionicConfigProvider.platform.android.views.transition('ios');
        $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
        $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
        $ionicConfigProvider.platform.android.tabs.style('standard');
        $ionicConfigProvider.platform.android.tabs.position('bottom');
        $ionicConfigProvider.platform.android.form.toggle('large');

        $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
        $ionicConfigProvider.platform.default.backButton.text(false);
    });
    myApp.constant('recordConstant', {
        recordSV: 'UFIDA.U9.ISV.AMMobile.QuerySV.IAttendenceQuerySV',
        IEnumCmd: 'UFIDA.U9.ISV.AMMobile.QueryEnumSV.IEnumQuerySV',
        SubmitCmd: 'UFIDA.U9.ISV.AMMobile.SubmitLeaveDocSV.ISubmitLeaveDocSV'

    });
    myApp.factory('RecordsService', ['$q', '$state', 'recordConstant', function ($q, $state, recordConstant) {
        var nowDate, nowYear, nowMonth;
        nowDate = new Date();
        nowYear = nowDate.getFullYear();
        nowMonth = nowDate.getMonth() + 1;
        var result = {},
            detailDatas = {},
            dates = {
                beginDate: "",
                endDate: "",
                endDate2: ""
            },
            largeMonth = ['01', '03', '05', '07', '08', '10', '12'],
            allData = {},
            selectData = {},
            timerPoint = {
                year: nowYear,
                month: nowMonth
            };
        //加载全部考勤。
        result.loadAllRecords = function () {
            var defer = $q.defer();
            u9.callSV({
                name: recordConstant.recordSV,
                params: ['Account1', 11],
                onSuccess: function (data) {
                    angular.forEach(data, function (info) {
                        var start = info.WorkFlowState.indexOf("(");
                        var end = info.WorkFlowState.indexOf(")");
                        if (start == -1 && end == -1) {
                            info.sname = info.WorkFlowState;
                            info.staus = "";
                        } else {
                            info.sname = info.WorkFlowState.substring(0, start);
                            info.staus = info.WorkFlowState.substring(start);
                        }
                    });
                    allData = data;
                    u9.hideLoading();
                    defer.resolve();
                },
                onFailure: function (err) {
                    u9.hideLoading();
                    defer.reject(err);
                }
            });
            return defer.promise;
        };
        //获取全部考勤
        result.getRecords = function () {
            return allData;
        };
        //加载全部缺勤原因
        result.loadAllSelectData = function () {
            var defer = $q.defer();
            u9.callSV({
                name: recordConstant.IEnumCmd,
                params: ['Account1'],
                onSuccess: function (data) {
                    selectData = data;
                    defer.resolve(selectData);
                },
                onFailure: function (err) {
                    defer.reject(err);
                }
            });
            return defer.promise;
        };
        //获取全部缺勤原因
        result.getSelectData = function () {
            return selectData;
        };

        result.SubmitFunction = function (data_fin) {
            var defer = $q.defer();
            u9.callSV({
                name: recordConstant.SubmitCmd,
                params: [data_fin],
                onSuccess: function (data) {
                    defer.resolve(data);
                },
                onFailure: function (err) {
                    defer.reject(err);
                }
            });
            return defer.promise;
        };

        result.initDate = function (data, flag_dir) {
            var m = data.split('-');
            var m1 = m[0];
            var m2 = m[1] - 0;
            var m3 = m[2] - 0;
            var m6 = m[2] - 1;
            var daysInMonth = new Array([0], [31], [28], [31], [30], [31], [30], [31], [31], [30], [31], [30], [31]);
            if (m1 % 4 == 0 && m1 % 100 != 0) {
                daysInMonth[2] = 29;
            }

            if (flag_dir == "left") {
                var m4 = m1 - 1;
                var m5 = m2 - 1;
            } else {
                var m4 = m1 - (-1);
                var m5 = m2 - (-1);
            }
            var m8 = m2;
            if (m2 != "10" && m2 != "11" && m2 != "12") {
                m2 = "0" + m2;
            }
            if (m3 < "10") {
                m3 = "0" + m3;
            }
            if (m6 < "10") {
                m6 = "0" + m6;
            }
            var m7 = m5;
            if (m5 != "10" && m5 != "11" && m5 != "12") {
                m5 = "0" + m5;
            }
            var uni1 = m1 + "-" + m2 + "-" + m3;
            var uni2 = m1 + "-" + m5 + "-" + m3;
            if (flag_dir == "left") {
                if (m2 - 1 == 0) {
                    uni2 = m4 + "-" + "12" + "-" + m3;
                }
                dates.beginDate = uni2;
                dates.endDate = uni1;
                var uni3 = m1 + "-" + m2 + "-" + m6;
                if (m6 == "00") {
                    m6 = daysInMonth[m7];
                    uni3 = m1 + "-" + m5 + "-" + m6;
                    if (m2 - 1 == 0) {
                        uni3 = m4 + "-" + "12" + "-31";
                    }
                }
                dates.endDate2 = uni3;
            } else {
                var uni3 = m1 + "-" + m5 + "-" + m6;
                if (m2 - (-1) == 13) {
                    uni2 = m4 + "-" + "01" + "-" + m3;
                    uni3 = m4 + "-" + "01" + "-" + m6;
                }
                dates.beginDate = uni1;
                dates.endDate = uni2;
                if (m6 == "00") {
                    m6 = daysInMonth[m8];
                    uni3 = m1 + "-" + m2 + "-" + m6;
                    if (m2 - (-1) == 13) {
                        uni3 = m1 + "-" + "12" + "-31";
                    }
                }
                dates.endDate2 = uni3;
            }
            return dates;
        };
        result.getDates = function () {
            return dates;
        };
        result.savaDetailDatas = function (data) {
            detailDatas = data;
        };
        result.getAbnormalSingleDetail = function () {
            if (detailDatas.WorkFlowState == "") {
                detailDatas.WorkFlowState = "正常";
            }
            var SingleInfo = {
                Date: detailDatas.Date,
                Result: detailDatas.Result,
                FormalGoToWorkTime: detailDatas.FormalGoToWorkTime,
                ActualGoToWorkTime: detailDatas.ActualGoToWorkTime,
                FormalGoOffWorkTime: detailDatas.FormalGoOffWorkTime,
                ActualGoOffWorkTime: detailDatas.ActualGoOffWorkTime,
                FormalAttendanceHours: detailDatas.FormalAttendanceHours,
                ActualAttendanceHours: detailDatas.ActualAttendanceHours,
                FormalPeriod: detailDatas.FormalPeriod,
                WorkFlowState: detailDatas.WorkFlowState,
                ActualPeriod: detailDatas.ActualPeriod,
                AbsenteeismHours: parseFloat(detailDatas.AbsenteeismHours),
                ActualOverTimeHours: parseFloat(detailDatas.ActualOverTimeHours),
                LeaveHours: parseFloat(detailDatas.LeaveHours)

            };
            return SingleInfo;
        };
        result.getAbnormalToDo = function () {
            var SingleInfo = {
                Date: detailDatas.Date,
                Result: detailDatas.Result,
                FormalGoToWorkTime: detailDatas.FormalGoToWorkTime,
                ActualGoToWorkTime: detailDatas.ActualGoToWorkTime,
                FormalGoOffWorkTime: detailDatas.FormalGoOffWorkTime,
                ActualGoOffWorkTime: detailDatas.ActualGoOffWorkTime,
                FormalAttendanceHours: detailDatas.FormalAttendanceHours,
                ActualAttendanceHours: detailDatas.ActualAttendanceHours,
                FormalPeriod: detailDatas.FormalPeriod,
                WorkFlowState: detailDatas.WorkFlowState,
                Employee: detailDatas.Employee,
                ID: detailDatas.ID,
                ActualPeriod: detailDatas.ActualPeriod,
                AbsenteeismHours: parseFloat(detailDatas.AbsenteeismHours),
                ActualOverTimeHours: parseFloat(detailDatas.ActualOverTimeHours),
                LeaveHours: parseFloat(detailDatas.LeaveHours)
            };
            return SingleInfo;
        };
        result.setTimerPoint = function (value) {
            timerPoint.year = value.year;
            timerPoint.month = value.month;
        };
        result.getTimerPoint = function () {
            return timerPoint;
        };
        result.getEndDate = function (value) {
            var y = value.year;
            var m = value.month;
            var fm;
            if (m < 10) {
                fm = '0' + m;
            } else {
                fm = m
            }
            if (largeMonth.indexOf(fm.toString()) > 0) {
                return {
                    month: fm,
                    day: 31
                }
            } else if (((y % 4 == 0 && y % 100 != 0) || (y % 100 == 0 && y % 400 == 0))
                && (m == 2)) {
                return {
                    month: fm,
                    day: 28
                };
            } else {
                return {
                    month: fm,
                    day: 30
                };
            }
        };
        result.formatDate = function (time) {
            var formatTime = time.split('-');
            return {
                year: formatTime[0],
                month: formatTime[1],
                day: formatTime[2]
            }
        };
        return result;
    }]);
    myApp.controller('HomeCtrl', function ($scope, $state, RecordsService) {
        $scope.allInfo = {};
        $scope.data = {
            flag1: true,
            flag2: false,
            color1: "button-light",
            color2: "none",
            leftBtn: "left_active",
            rightBtn: "right"
        };
        $scope.getActive = function (index) {
            switch (index) {
                case 0:
                    $scope.data = {
                        flag1: true,
                        flag2: false,
                        color1: "button-light",
                        color2: "none",
                        leftBtn: "left_active",
                        rightBtn: "right"
                    };
                    break;
                case 1:
                    $scope.data = {
                        flag1: false,
                        flag2: true,
                        color1: "none",
                        color2: "button-light",
                        leftBtn: "left",
                        rightBtn: "right_active"
                    };
                    break;
                default:
                    $scope.data = {
                        flag1: true,
                        flag2: false,
                        color1: "button-light",
                        color2: "none",
                        leftBtn: "left_active",
                        rightBtn: "right"
                    };
            }
        }

        //向左滑动事件
        $scope.prevMonth = function () {
            var point, showYear, showMonth;
            var data = allInfo;
            point = RecordsService.getTimerPoint();
            if (point.month == 1) {
                showYear = point.year - 1;
                showMonth = 12;
            } else {
                showYear = point.year;
                showMonth = point.month - 1;
            }
            if (showYear >= (new Date()).getFullYear()) {
                var value = RecordsService.getEndDate({
                    year: showYear,
                    month: showMonth
                });

                $scope.beginDate = showYear + '-' + value.month + '-' + '01';
                $scope.endDate = showYear + '-' + value.month + '-' + value.day;
                RecordsService.setTimerPoint({
                    year: showYear,
                    month: showMonth
                });

                //异常考勤页面list
                $scope.abnormalDetailInfo = [];
                for (var i in data) {
                    if (data[i].Result == "异常" && data[i].WorkFlowState != "补卡(已审批)" && data[i].WorkFlowState != "请假(已审批)" && data[i].Date < $scope.endDate && data[i].Date >= $scope.beginDate) {
                        $scope.abnormalDetailInfo.push(data[i]);
                    }
                }
                //全部考勤页面list
                $scope.normalDetailInfo = [];
                for (var i in data) {
                    if (data[i].Date <= $scope.endDate && data[i].Date >= $scope.beginDate) {
                        $scope.normalDetailInfo.push(data[i]);
                    }
                }
            }
        };
        $scope.nextMonth = function () {
            var point, showYear, showMonth;
            point = RecordsService.getTimerPoint();
            var data = allInfo;
            if (point.month == 12) {
                showYear = point.year + 1;
                showMonth = 1;
            } else {
                showYear = point.year;
                showMonth = point.month + 1;
            }
            if (showYear <= (new Date()).getFullYear()) {
                var value = RecordsService.getEndDate({
                    year: showYear,
                    month: showMonth
                });

                $scope.beginDate = showYear + '-' + value.month + '-' + '01';
                $scope.endDate = showYear + '-' + value.month + '-' + value.day;

                RecordsService.setTimerPoint({
                    year: showYear,
                    month: showMonth
                });

                $scope.abnormalDetailInfo = [];
                for (var i in data) {
                    if (data[i].Result == "异常" && data[i].WorkFlowState != "补卡(已审批)" && data[i].WorkFlowState != "请假(已审批)" && data[i].Date < $scope.endDate && data[i].Date >= $scope.beginDate) {
                        $scope.abnormalDetailInfo.push(data[i]);
                    }
                }
                $scope.normalDetailInfo = [];
                for (var i in data) {
                    if (data[i].Date <= $scope.endDate && data[i].Date >= $scope.beginDate) {
                        $scope.normalDetailInfo.push(data[i]);
                    }
                }
                if ($scope.normalDetailInfo.length == 0 && $scope.period > $scope.periodInt) {
                    u9.alert("下一期间无记录！");
                    $scope.prevMonth();
                }
            }
        };

        //点击考勤
        $scope.changeAll = function () {
            $state.go("abnormalAll");
        };
        //单笔补考勤页面
        $scope.getAbnormalDo = function (data) {
            RecordsService.savaDetailDatas(data);
            $state.go("abnormalSingle");
        };
        //日考勤异常明细
        $scope.abnormalSingleDi = function (data) {
            RecordsService.savaDetailDatas(data);
            $state.go("abnormalDetail");
        };
        $scope.dataInit = function () {
            var timerPoint = RecordsService.getTimerPoint();
            var value = RecordsService.getEndDate({
                year: timerPoint.year,
                month: timerPoint.month
            });
            $scope.beginDate = timerPoint.year + '-' + value.month + '-' + '01';
            $scope.endDate = timerPoint.year + '-' + value.month + '-' + value.day;

            var records = RecordsService.getRecords();
            //if ($scope.beginDate == null) {
            //    if (records[0] != null) {
            //        var dates = RecordsService.initDate(records[0].Split, 'left');
            //        $scope.beginDate = dates.beginDate;
            //        $scope.endDate = dates.endDate;
            //        $scope.endDate2 = dates.endDate2;
            //        $scope.periodInt = $scope.period = records[0].Period;
            //    } else {
            //        u9.alert("未找到该员工对应的信息");
            //    }
            //    //主页赋值记录值
            //    allInfo = records;
            //}
            allInfo = records;
            //异常考勤页面list
            $scope.abnormalDetailInfo = [];
            for (var i in records) {
                if (records[i].Result == "异常" && records[i].WorkFlowState != "补卡(已审批)"
                    && records[i].WorkFlowState != "请假(已审批)" && records[i].Date <= $scope.endDate
                    && records[i].Date >= $scope.beginDate) {

                    $scope.abnormalDetailInfo.push(records[i]);
                }
            }
            //全部考勤页面list
            $scope.normalDetailInfo = [];
            for (var i in records) {
                if (records[i].Date <= $scope.endDate && records[i].Date >= $scope.beginDate) {
                    $scope.normalDetailInfo.push(records[i]);
                }
            }
            //$state.go("home");
        };
        //初始化页面
        $scope.dataInit();
    });
    myApp.controller('abnormalAllCtrl', function ($scope, RecordsService, $state) {
        var allInfo = {};
        //返回
        var returnHome = function () {
            if ($scope.beginDate == null) {
                if (allInfo[0] != null) {
                    var dates = RecordsService.initDate(allInfo[0].Split, 'left');
                    $scope.beginDate = dates.beginDate;
                    $scope.endDate = dates.endDate;
                    $scope.endDate2 = dates.endDate2;
                    $scope.periodInt = $scope.period = allInfo[0].Period;
                } else {
                    u9.alert("未找到该员工对应的信息");
                }
            }
            //异常考勤页面list
            $scope.abnormalDetailInfo = [];
            for (var i in allInfo) {
                if (allInfo[i].Result == "异常"
                    && allInfo[i].WorkFlowState != "补卡(已审批)"
                    && allInfo[i].WorkFlowState != "请假(已审批)"
                    && allInfo[i].WorkFlowState != "补卡(待审批)"
                    && allInfo[i].WorkFlowState != "请假(待审批)"
                    && allInfo[i].Date <= $scope.endDate
                    && allInfo[i].Date >= $scope.beginDate) {
                    $scope.abnormalDetailInfo.push(allInfo[i]);
                }
            }
            //全部考勤页面list
            $scope.normalDetailInfo = [];
            for (var i in allInfo) {
                if (allInfo[i].Date < $scope.endDate && allInfo[i].Date >= $scope.beginDate) {
                    $scope.normalDetailInfo.push(allInfo[i]);
                }
            }
            $state.go("home");
        };

        //upload all records
        $scope.submitAll = function (data) {
            var data_fin = [];
            for (var i in data) {
                if (data[i].category != null) {
                    var temp = {
                        Employee: " ",
                        ID: data[i].ID,
                        Category: data[i].category
                    };
                    data_fin.push(temp);
                }
            }
            RecordsService.SubmitFunction(data_fin).then(function () {
                returnHome();
            }, function () {
                returnHome();
            });
        };

        $scope.dataInit = function () {
            var records = RecordsService.getRecords();
            var timerPoint = RecordsService.getTimerPoint();
            var value = RecordsService.getEndDate({
                year: timerPoint.year,
                month: timerPoint.month
            });
            $scope.beginDate = timerPoint.year + '-' + value.month + '-' + '01';
            $scope.endDate = timerPoint.year + '-' + value.month + '-' + value.day;
            allInfo = records;
            $scope.AbsenseDetailInfo = [];
            for (var i in records) {
                if (records[i].Result == "异常"
                    && allInfo[i].WorkFlowState != "补卡(已审批)"
                    && allInfo[i].WorkFlowState != "请假(已审批)"
                    && allInfo[i].WorkFlowState != "补卡(待审批)"
                    && allInfo[i].WorkFlowState != "请假(待审批)"
                    && records[i].Date <= $scope.endDate
                    && records[i].Date >= $scope.beginDate) {
                    $scope.AbsenseDetailInfo.push(records[i]);
                }
            }
            $scope.enumInfo = RecordsService.getSelectData();
        };
        $scope.dataInit();
    });
    myApp.controller('abnormalSingleCtrl', function ($scope, $state, RecordsService) {
        $scope.absence = {
            reasons: '000'
        };
        //返回
        var allInfo = RecordsService.getRecords();
        var returnHome = function () {
            if ($scope.beginDate == null) {
                if (allInfo[0] != null) {
                    var dates = RecordsService.initDate(allInfo[0].Split, 'left');
                    $scope.beginDate = dates.beginDate;
                    $scope.endDate = dates.endDate;
                    $scope.endDate2 = dates.endDate2;
                    $scope.periodInt = $scope.period = allInfo[0].Period;
                } else {
                    u9.alert("未找到该员工对应的信息");
                }
            }
            //异常考勤页面list
            $scope.abnormalDetailInfo = [];
            for (var i in allInfo) {
                if (allInfo[i].Result == "异常" && allInfo[i].WorkFlowState != "补卡(已审批)"
                    && allInfo[i].WorkFlowState != "请假(已审批)" && allInfo[i].Date < $scope.endDate
                    && allInfo[i].Date >= $scope.beginDate) {
                    $scope.abnormalDetailInfo.push(allInfo[i]);
                }
            }
            //全部考勤页面list
            $scope.normalDetailInfo = [];
            for (var i in allInfo) {
                if (allInfo[i].Date < $scope.endDate && allInfo[i].Date >= $scope.beginDate) {
                    $scope.normalDetailInfo.push(allInfo[i]);
                }
            }
            $state.go("home");
        };
        //日考勤异常明细
        $scope.abnormalSingle = function (data) {
            var mm = $scope.absence.reasons;
            var data_fin = [];
            if (mm != '000') {
                var temp = {
                    Employee: " ",
                    ID: data.ID,
                    Category: mm
                };
                data_fin.push(temp);
            } else {
                u9.alert("请选择补填类型!");
                return;
            }
            RecordsService.SubmitFunction(data_fin).then(function (obj) {
                console.log(obj);
                $state.go("abnormalDetail");
            }, function (er) {
                returnHome();
            });
            if (mm == "ForgetPunch") {
                //补卡(待审批)
                data.WorkFlowState = "补卡(待审批)"
            } else {
                //请假(待审批)
                data.WorkFlowState = "请假(待审批)"
            }
            RecordsService.savaDetailDatas(data);
            $scope.SingleInfo = RecordsService.getAbnormalSingleDetail();
        };
        $scope.dataInit = function () {
            $scope.enumInfo = RecordsService.getSelectData();
            $scope.SingleInfo = RecordsService.getAbnormalToDo();
        };
        $scope.dataInit();

    });
    myApp.controller('abnormalDetailCtrl', function ($scope, $state, RecordsService) {
        $scope.SingleInfo = RecordsService.getAbnormalSingleDetail();
        $scope.goHome = function () {
            $state.go("home");
        }
    });

});